const path = require('path');
const { getWeCodeConfig, processSendError } = require('../config/utils');
const fs = require('fs');
const { log } = require('../../log');
const { createMap } = require('../config/create-map');

process.on('message', _data => {
  try {
    const data = JSON.parse(_data);
    const { cmd } = data;
    if (cmd === 'build') {
      build(data);
    }
  } catch (error) {
    log('编译报错 message：', error);
  }
});

['SIGINT', 'SIGTERM'].forEach(function(sig) {
  process.on(sig, function(error) {
    process.exit();
  });
});

function build(args = {}) {
  const { env } = args;
  const {
    WECODE_ENV,
    WECODE_APP_PATH,
    WECODE_DEBUG,
    WECODE_ESLINT_PATH,
    // @remove-on-eject-begin
    WECODE_BOOTSTRAP_PATH = null, // jsapi common asar包,供本地调试用
    // @remove-on-eject-end
    WECODE_JSAPI_ASAR_PATH = null, // asar 补丁文件
    RUNTIME_PATH
  } = env;
  delete require.cache[require.resolve('../vue.config.js')];

  process.env.WECODE_ENV = WECODE_ENV;
  process.env.NODE_ENV = WECODE_ENV;
  process.env.WECODE_ESLINT_PATH = WECODE_ESLINT_PATH;
  process.env.WECODE_JSAPI_ASAR_PATH = WECODE_JSAPI_ASAR_PATH;
  process.env.RUNTIME_PATH = RUNTIME_PATH || path.join(process.cwd(), '..');

  // @remove-on-eject-begin
  if(WECODE_BOOTSTRAP_PATH) {
    const appPathNodeModules = path.resolve(WECODE_APP_PATH ,'node_modules');
    const bootstrap = require(WECODE_BOOTSTRAP_PATH);
    const nodeModulesPath = path.resolve(__dirname ,'../node_modules');
    bootstrap.enableASARSupport(nodeModulesPath, fs.existsSync(appPathNodeModules) ? appPathNodeModules : null);
  }
  // @remove-on-eject-end
  

  const Service = require('@vue/cli-service');
  const runtimePath = path.join(__dirname, '..');
  const service = new Service(runtimePath);

  const { wecodeJson } = getWeCodeConfig(WECODE_APP_PATH);

  if(WECODE_DEBUG === true) {
    wecodeJson.debug = true;
  }

  const { debug, eslint } = wecodeJson;
  log(`Env: ${WECODE_ENV}, Debug:${debug}.`);
  process.env.ESLINT = eslint;

  // 设置环境变量，供webpack使用
  process.env.WECODE_APP_PATH = WECODE_APP_PATH;
  process.env.WEOCDE_PROCESS_MESSAGE = JSON.stringify(args);

  return service
    .run('build')
    .then((data) => {

      // 进行map文件抽起
      createMap(path.join(WECODE_APP_PATH, "build/apps/local/0/"));

      if (process && process.send) {
        process.send({
          status: 'done',
          request: args
        });
      }
      return data;
    })
    .catch(error => {
      log('编译出错！', error);
      if (process && process.send) {
        process.send({
          status: 'error',
          request: args,
          message: {
            tip: 'Build fail.',
            details: error
          }
        });
      }
      return error;
    });
}

module.exports = build;
